/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mmt_server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import Message.Message;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.beans.PropertyVetoException;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 *
 * @author CUCAINHO
 */
public class MMT_SERVER {

    public static ArrayList<Socket> lstClientSocket;		
    public static ServerSocket server ;
    
    
    /// view desktop
    
     private static JDesktopPane desktop = new JDesktopPane();    
    private static JInternalFrame interFrame = new JInternalFrame("Client Screen",
                                                            true, true, true);
    private static JPanel cPanel = new JPanel();
    
     private static JFrame frame = new JFrame();
     private static int  catchPicture = 1;
    
    ///
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       try
        {
                ImageIcon imagesour = createImageIcon("images/img.jpg");
                 
                SaveImage(imagesour, "congtt.jpg");
                drawGUI();
                lstClientSocket = new ArrayList<Socket>();

                server = new ServerSocket(3211);

                do
                {	//System.out.print("a");
                    try{
                        Listen();
                    }catch(Exception e)
                    {
                        break;
                    }
                        //System.out.print("end a");
                }
                while (true);

        }
        catch(Exception e)
        {
                System.out.println("Error in Main!");
        }	
        
    }
    
    public  void StartMain() throws IOException{
        
        lstClientSocket = new ArrayList<Socket>();
        server = new ServerSocket(3211);

        do
        {	//System.out.print("a");
            try{
                Listen();
            }catch(Exception e)
            {
                break;
            }
                //System.out.print("end a");
        }
        while (true);
                
    }
    
    public static ImageIcon createImageIcon(String path) {
          java.net.URL imgURL = MMT_SERVER.class.getResource(path);
          if (imgURL != null) {
              return new ImageIcon(imgURL);
          } else {
              System.err.println("Couldn't find file: " + path);
              return null;
          }
      }
    
    public static void SaveImage(ImageIcon imagesour , String path){
         /// writer image
        
        try{
            
            Image img = imagesour.getImage();//TYPE_BYTE_ARGB
               //BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_BYTE_ARGB);
            BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bi.createGraphics();
            // Draw img into bi so we can write it to file.
            
            g2.drawImage(img, 0, 0, null);
       
            g2.dispose();
            
            try {
                // Now bi contains the img.
                // Note: img may have transparent pixels in it; if so, okay.
                // If not and you can use TYPE_INT_RGB you will get better
                // performance with it in the jvm.
                ImageIO.write(bi, "jpg", new File(path));

                //BufferedImage bi = new BufferedImage(img.getWidth(null),img.getHeight(nul l), BufferedImage.TYPE_BYTE_ARGB );
            } catch (IOException ex) {
                System.out.println("loi khi write image: "+ex.toString());
                Logger.getLogger(MMT_SERVER.class.getName()).log(Level.SEVERE, null, ex);
            }
        }catch(Exception ex){
            System.out.println("Loi wite: " + ex.toString());
                    
        }

        
    }
    
    public static  void Listen() throws InterruptedException
    {
            try {			

                    System.out.println("Waiting for a Client connect...");

                    Socket ss = server.accept(); //synchronous			
                    lstClientSocket.add(ss);			
                    System.out.println("count accept " + lstClientSocket.size() +" name: "+  ss.toString());			
                    HandClient(ss);// nhan data tu client.


            }
            catch (IOException e) {

                    System.out.println("Loi khi listen client."+ e.toString());

            }

    }
	

	
	
	public static void HandClient(Socket ss)
	{
		try
		{						
                    ReciveClient rc = new ReciveClient(ss);			
		
                    /// 
                    
                    
		}
		catch(Exception e)
		{
                    System.out.println("Error in function HandClient!");
		}                
               
		
		
	}
        
        public static void HandMessage(Message ms , Socket socket){
            
            int type;
            System.out.println("zo ham hand messagee");
            type = ms.GetType();
            switch(type){
                case 1: // chat
                    HandChat(ms);
                    break;
                case 2:
                    break;
                case 3:
                    break;
                case 4:
                    break;
                case 5:
                    HandRemote(ms , socket);
                    break;
                case 6:
                    break;
                case 7:
                    break;
                case 8:
                    break;
                case 9:
                    break;
                    
            }            
        }
        
        public static void  HandChat(Message ms){
            System.out.println("ham chat: ");
            String str = ms.GetData().toString();
            System.out.println("Client: " + str);
        }
        
        public static void HandFile(Message ms){
            
        }
        
        public static void XL_Rectangle(Message ms , Socket socket){
           
           System.out.println("XL_ REC========================================================================================"); 
           Rectangle clientScreenDim = null;            
           clientScreenDim =(Rectangle) ms.GetData();
           new ClientCommandsSender(socket,cPanel,clientScreenDim);
        
        }
        
        public static void HandRemote(Message ms , Socket socket){
            int option = ms.GetOption();
            
            switch(option){
                
                case 1:
                   
                    break;
                case 2:
                    XL_NhanHinhView(ms);
                    break;
                case 3:
                     XL_Rectangle(ms , socket);
                    break;    
                default:
                    break;
            }
            
        }
        
        // view déktop
        public static void drawGUI(){
            frame.add(desktop,BorderLayout.CENTER);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            //Show the frame in a maximized state
            frame.setExtendedState(frame.getExtendedState()|JFrame.MAXIMIZED_BOTH);
            frame.setVisible(true);
    }
        
         public static void drawGUIView(){
            interFrame.setLayout(new BorderLayout());
            interFrame.getContentPane().add(cPanel,BorderLayout.CENTER);
            interFrame.setSize(100,100);
            interFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            desktop.add(interFrame);
            try {
                //Initially show the internal frame maximized
                interFrame.setMaximum(true);
            } catch (PropertyVetoException ex) {
                ex.printStackTrace();
            }
            //this allows to handle KeyListener events
            cPanel.setFocusable(true);
            interFrame.setVisible(true);
     }
        
        public static void XL_NhanHinhView(Message ms){
            
            System.out.println("zo ham hien thi hinh");
            catchPicture = catchPicture+1;
           // String str = (String)ms.GetData();
           // System.out.println("data: " + str);
           
            /*System.out.println("Nhan hinh.");
            
            JFrame frame = new JFrame();
             frame = new JFrame("QUẢN LÝ HỌC SINH");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);*/
             
            ImageIcon imageIcon = new ImageIcon();
             imageIcon = (ImageIcon)ms.GetData();
            
             if(catchPicture == 10){
                 SaveImage(imageIcon, "hinhcxlient_"+catchPicture+".jpg");
             }
             
             
             Image image = imageIcon.getImage();
             image = image.getScaledInstance(cPanel.getWidth(),cPanel.getHeight()
                                                        ,Image.SCALE_FAST);
                    
              Graphics graphics = cPanel.getGraphics();
             // graphics.drawImage(image, 0, 0, 100, 100, cPanel);
             graphics.drawImage(image, 0, 0, cPanel.getWidth(),cPanel.getHeight(),cPanel);
               
           
             /*JPanel p = new JPanel();
             JLabel lb = new JLabel(img);
             lb.setSize(800,800);
             
             p.add(lb);
             frame.add(p);
             frame.setSize(800, 800);
             frame.setVisible(true);*/
             
                    
            
        }
          
        public static void HandViewDesktop(Message ms){
            
        }
            
        public static void HandShell(Message ms){
            
        }              
      
}

 class  ReciveClient extends MMT_SERVER implements Runnable { 
	
	private Socket theclient;  
	private ObjectInputStream in;
	public ReciveClient (Socket theclient) { 
		this.theclient = theclient; 		
		Thread t = new Thread(this); 
		t.start(); 
	} 
        
        public static void SendToClient(Socket theclient) throws IOException{           
             
            ObjectOutputStream out = new ObjectOutputStream(theclient.getOutputStream());
            System.out.println("Send Client! ");
            Object obj = new String("Server!!!");
            Message mssend = new Message(1,1,obj);
            out.writeObject(mssend);
        }
        
        public static void SendRequestViewDesktop(Socket theclient) throws IOException{ 
	 ObjectOutputStream out = new ObjectOutputStream(theclient.getOutputStream());
            System.out.println("Send Request view desktop ");
            Object obj = new String("Server!!!");
            Message mssend = new Message(5,1,obj);
            out.writeObject(mssend);
            drawGUIView();
            
        }
	public void run() {             
                
            int k = 0;
		while(true){
                    System.out.println("nghe lan thu: " + k);
                /* if(k % 2 == 0){
                        try {
                            System.out.println("send data to client");
                            SendToClient(theclient);
                        } catch (IOException ex) {
                            Logger.getLogger(ReciveClient.class.getName()).log(Level.SEVERE, null, ex);
                        }
                  }*/
                  if(k == 0){ // send yeu cau view desktop
                        try {
                            System.out.println("Send yeu cau xem !!!");
                            SendRequestViewDesktop(theclient);
                        } catch (IOException ex) {
                            Logger.getLogger(ReciveClient.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        
                        /// nhan move tu cac cai khac
                         
                         
                  }
                  
		try 
		{  
                     Message ms = new Message();
                  
                  try{
                        in = new ObjectInputStream(theclient.getInputStream());
                       
                  }
                  catch(Exception ex){
                      System.out.println("Loi new input stream" + ex.toString());
                  }
                try {
                       ms = (Message)in.readObject(); // doc message                  
                    } catch (Exception ex) {
                        System.out.println("Loi khi doc message." + ex.toString());
                        ex.printStackTrace();
                        //break;
                       // Logger.getLogger(ReciveClient.class.getName()).log(Level.SEVERE, null, ex);
                    }
                        
                        //while(ms != null) {	
                        if(ms != null) {
                            try
                            {                                    
                                HandMessage(ms ,theclient );				
                            }catch(Exception ex){
                                System.out.println("message null!");

                            }                                    
                              
			} 
                      	
		//System.out.println("Close socket in server!");		
		//this.lstClientSocket.remove(theclient);		
		//out.flush();	
		//out.close();
		//in.close(); 	
		//theclient.close(); 	
                k++;
                
		} 
		catch (Exception e) { 
                        System.out.println("Client Disconnect! in server." + e.toString() );
                        
                       /* try {
                            theclient.close();
                        } catch (IOException ex) {
                            Logger.getLogger(ReciveClient.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;*/
			//e.printStackTrace(); 
		}
                
                k++;
	} 
        }
	
}